package com.whitedust.top50;

import java.util.Map;
import java.util.Stack;

/**
 * @author A
 * @since 2025/11/7 12:56
 */

public class Top48 {
    public int longestValidParentheses(String s) {
        int maxLen = 0;
        Stack<Integer> st = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ')' && !st.isEmpty()) {
                Integer peek = st.peek();
                if (s.charAt(peek) == '(') {
                    st.pop();
                    if(st.isEmpty())maxLen = Math.max(maxLen, i+1);
                    else maxLen = Math.max(maxLen, i - st.peek());
                } else {
                    st.push(i);
                }
            } else {
                st.push(i);
            }
        }
        return maxLen;
    }
}
